using System.ServiceModel.Syndication;
using System.Web.Mvc;
using System.Xml;

namespace etcetera.Mvc.ActionResults
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class FeedResult : ActionResult
    {
        protected string _contentType = "text/xml";
        protected FeedType _feedType = FeedType.Rss20;
        protected SyndicationFeedFormatter _formatter;

        public enum FeedType
        {
            Atom10,
            Rss20
        }
        
        /// <summary>
        /// Gets or sets the feed.
        /// </summary>
        /// <value>The feed.</value>
        public SyndicationFeed Feed { get; set; }

        /// <summary>
        /// Enables processing of the result of an action method by a custom type that inherits from <see cref="T:System.Web.Mvc.ActionResult"/>.
        /// </summary>
        /// <param name="context">The context within which the result is executed.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = _contentType;

            switch (_feedType)
            {
                case FeedType.Atom10:
                    _formatter = new Atom10FeedFormatter(Feed);
                    break;
                default:
                    _formatter = new Rss20FeedFormatter(Feed);
                    break;
            }

            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))
            {
                _formatter.WriteTo(writer);
            }
        }
    }
}